package cn.zhaoyuening.zshop4j.manager.service.impl;

import cn.zhaoyuening.zshop4j.common.bean.EasyUiListResult;
import cn.zhaoyuening.zshop4j.common.bean.ZShop4jResponceResult;
import cn.zhaoyuening.zshop4j.common.utils.RandomIdUtils;
import cn.zhaoyuening.zshop4j.manager.mapper.TbItemDescMapper;
import cn.zhaoyuening.zshop4j.manager.pojo.TbItemDesc;
import cn.zhaoyuening.zshop4j.manager.pojo.TbItemExample;
import cn.zhaoyuening.zshop4j.manager.service.ItemService;
import cn.zhaoyuening.zshop4j.manager.pojo.TbItem;
import cn.zhaoyuening.zshop4j.manager.mapper.TbItemMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by Zhao on 2017/4/3.
 */
@Service("itemService")
public class ItemServiceImpl implements ItemService {
    private TbItemMapper itemMapper;
    @Autowired
    private TbItemDescMapper itemDescMapper;
    @Override
    public TbItem findById(Long id) {
        TbItem item = itemMapper.selectByPrimaryKey(id);
        return item;
    }

    @Override
    public EasyUiListResult<TbItem> findAllByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<TbItem> itemList = itemMapper.selectByExample(new TbItemExample());
        PageInfo<TbItem> itemPageInfo = new PageInfo<TbItem>(itemList);
        EasyUiListResult<TbItem> itemEasyUiListResult = new EasyUiListResult<>();
        itemEasyUiListResult.setRows(itemPageInfo.getList());
        itemEasyUiListResult.setTotal(itemPageInfo.getTotal());
        return itemEasyUiListResult;
    }

    @Override
    public int deleteById(Long id) {
        int result = itemMapper.deleteByPrimaryKey(id);
        return result;
    }

    @Override
    public ZShop4jResponceResult addItem(TbItem item, String desc) {

        //产生唯一ID
        long id = RandomIdUtils.genItemId();
        item.setId(id);
        //设置状态 1-正常 2-下架 3-删除
        item.setStatus((byte) 1);
        //设置日期
        Date date = new Date();
        item.setCreated(date);
        item.setUpdated(date);
        //商品描述
        TbItemDesc itemDesc = new TbItemDesc();
        itemDesc.setItemDesc(desc);
        itemDesc.setItemId(id);
        itemDesc.setCreated(date);
        itemDesc.setUpdated(date);
        int itemInsertResult = itemMapper.insert(item);
        int itemDescInsertResult = itemDescMapper.insert(itemDesc);
        return ZShop4jResponceResult.ok();
    }

    @Autowired
    public void setItemMapper(TbItemMapper itemMapper) {
        this.itemMapper = itemMapper;
    }
}
